// axios封装
import { message } from "antd"
import axios from "axios"
import { getToken } from "./storage"
import store from "@/store"
import { logout } from "@/store/action/login"
import history from "./history"

const instance = axios.create({
  baseURL: "http://geek.itheima.net/V1_0",
  timeout: 5000,
})

// 配置请求拦截器
instance.interceptors.request.use(
  function (config) {
    const token = getToken()
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 配置响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response
  },
  function (error) {
    if (!error.response) {
      message.error("网络繁忙，请稍后重试", 1)
      return Promise.reject(error)
    }
    if (error.response.status === 401) {
      // token过期
      message.error("登录信息过期", 1)
      // 清除token
      store.dispatch(logout())
      // 跳转登录
      history.push("/login")
    }
    return Promise.reject(error)
  }
)

export default instance
